<?php
declare (strict_types=1);

namespace app\exam\logic;

use think\facade\Db;
use think\facade\Cache;
use app\common\exception\LogicException;
use app\exam\model\TopicCollect as TopicCollectModel;

/**
 * 试题收藏逻辑层
 */
class TopicCollect extends TopicCollectModel
{

	/**
	 * 用户是否收藏试题
	 * Author 亓官雨树<lucky.max@foxmail.com>
	 * Date 2021-03-05
	 * @param string $value [description]
	 */
	public function hasUserCollectedTopic($topic_id)
	{
		$data = $this->whereUserId(request()->mid)->whereTopicId($topic_id)->findOrEmpty();

		return $data->isEmpty() ? 0 : 1;
	}

	/**
	 * 收藏题目
	 * Author 亓官雨树<lucky.max@foxmail.com>
	 * Date 2021-03-05
	 * @param  [type] $topic_id [description]
	 * @return [type]           [description]
	 */
	public function collectTopic($param)
	{
		// 验证数据
		$this->getValidate()->scene('collect')->failException()->check($param);
		// 参数
		$mid 		= request()->mid;
		$topic_id 	= $param['topic_id'];
		$status 	= $param['status'];
		$success 	= $status ? '已收藏' : '已取消收藏';

		if ( $status ) {
			// 收藏
			$data 		= $this->whereTopicId(current(explode(',', $topic_id)))->whereUserId($mid)->findOrEmpty();
			if ( $data->isEmpty() ) {
				$res = $this::create([
					'topic_id'  => $topic_id,
					'user_id'	=> $mid
				]);
				if ( $res->isEmpty() ) throw new LogicException("收藏失败");
			}
		} else {
			// 取消收藏
			$this->whereIn('topic_id', $topic_id)->whereUserId($mid)->delete();
		}

		return $success;
	}

	/**
	 * 收藏列表
	 * Author 亓官雨树<lucky.max@foxmail.com>
	 * Date 2021-03-18
	 * @return [type] [description]
	 */
	public function getCollectList()
	{
		// 参数
		$mid 	= request()->mid;
		$question_type_arr = Topic::getQuestionTypeArr();
		// 数据
		$data 	= $this
			->with(['topic_basic'])
			->whereUserId($mid)
			->order('create_time DESC')
			->paginate($this->getListRows())
			->toArray()
		;

		foreach ($data['data'] as $key => &$value) {
			if (!$value['question_type']) {
				unset($data['data'][$key]);
			} else {
				$value['question_type_text'] = $question_type_arr[$value['question_type']];
			}
			$value['topic_title']    = app(Common::class)->removeMaterial($value['topic_title']??'');
		}

		$data['data'] = array_values($data['data']);
		
		return $data;
	}
}